import {Component, ViewChild} from '@angular/core';
import {PaginatorForm} from "../../../models/paginatorForm";
import {DatePipe} from "@angular/common";

import {UserService} from "../../service/user.service";
import {PromptService} from "../../../util/prompt/prompt.service";
import {RoleTypePipe} from "../../../util/pipe/rolelType.pipe";
import {CommonService} from "../../../util/common.service";
import {RoleEntity} from "../../model/roleEntity";
import {UserEditForm} from "../../model/userEditForm";
import {NavigationBarService} from "../../../site/service/navigationBar.service";
import {ConfirmInfo} from "../../../util/comfirm/typeOne/models/confirmInfo";
import {FilterForm} from "../../../models/filterForm";
import {FilterConditionForm} from "../../../models/filterConditionForm";
import {FilterConditionFormTypeEnum} from "../../../models/filterConditionFormTypeEnum";
import {FilterConditionFormLeftTypeEnum} from "../../../models/filterConditionFormLeftTypeEnum";
declare var $: any;
@Component({
    moduleId: module.id,
    selector: 'userList-component',
    templateUrl: "./userList.html"
})


export class UserListComponent {

    @ViewChild('table') table: any;
    @ViewChild('editModal') editModal: any;
    @ViewChild('searchModal') searchModal: any;
    userEditForm: UserEditForm = new UserEditForm()
    roleList: RoleEntity[] = []
    deleteUserId: number;
    @ViewChild('confrimDelete') confrimDelete: any;

    constructor(private userService: UserService, private promptService: PromptService, private commonService: CommonService) {
        this.commonService.setNavigationBar("用户列表")
    }

    async ngOnInit() {
        this.getUserList();
        this.getRoleList();
    }

    filterForm: FilterForm = new FilterForm(
        [
            new FilterConditionForm("username", "like", FilterConditionFormTypeEnum.common),
            new FilterConditionForm("realname", "like", FilterConditionFormTypeEnum.common),
            new FilterConditionForm("roleId", "eq", FilterConditionFormTypeEnum.common, FilterConditionFormLeftTypeEnum.int, false),
            // new FilterConditionForm("email", "like", FilterConditionFormTypeEnum.common)
            // new FilterConditionForm("roleList", "like", FilterConditionFormTypeEnum.common)
        ]
    );

    initSearch() {
        this.filterForm.initSearchData();
        this.search();
    }

    search() {
        $(this.searchModal.nativeElement).modal("hide");
        $(this.table.nativeElement).bootstrapTable("refresh");
    }

    getRoleList() {
        this.userService.getRoleAllList().then((data)=> {
            if (data.success) {
                this.roleList = data.result
            } else {
                this.promptService.warning(data.error.message)
            }

        })
    }

    getUserList() {
        $(this.table.nativeElement).bootstrapTable({
            url: this.commonService.getRequestProUrl() + "/api/user/get_user_list",
            dataType: "json",
            method: "post",
            pagination: true, //分页
            // clickToSelect: true,
            // singleSelect: false,
            sidePagination: "server", //服务端处理分页
            toolbar: '#toolbar',
            queryParams: (params: any)=> {
                return {
                    limit: params.limit,   //页面大小
                    offset: params.offset,
                    filterConditions: this.filterForm.operateSearchData()
                }
            },
            columns: [
                {
                    title: '登录账号',
                    field: 'username',
                }, {
                    title: '真实姓名',
                    field: 'realname',
                }, {
                    title: '联系电话',
                    field: 'tel',
                }, {
                    title: '邮箱',
                    field: 'email',
                }, {
                    title: '角色',
                    field: 'roleList',
                    formatter: (value: any, row: any, index: any) => {
                        let result = "";
                        for (let role of value) {
                            result += '<span class="label label-info" style="margin-right: 5px">' + role.name + '</span>'
                        }
                        return result
                    }
                }, {
                    title: '修改日期',
                    field: 'updateAt',
                    formatter: (value: any, row: any, index: any) => {
                        let result: any = new DatePipe("en-US").transform(value, "yyyy年MM月dd日");
                        return result
                    }
                }, {
                    title: '操作',
                    field: 'operate',
                    formatter: (value: any, row: any, index: any) => {
                        let result: any = ""
                        var style = this.commonService.getTableOperateBtnCss()
                        result += '<span  title="编辑" class="edit  fa fa-pencil" style="' + style + '"></span>'
                        result += '<span  title="删除" class="delete  fa fa-trash" style="' + style + '"></span>'
                        return result;
                    },
                    events: {
                        'click .edit': (e: any, value: any, row: any, index: any)=> {
                            this.userEditForm = Object.assign(new UserEditForm(), row)
                            this.userEditForm.password = ""
                            this.userEditForm.repassword = ""
                            if (row.roleList.length > 0) {
                                this.userEditForm.roleId = row.roleList[0].id
                            }
                            $(this.editModal.nativeElement).modal("show")
                        },
                        'click .delete': (e: any, value: any, row: any, index: any)=> {
                            this.userService.getUserDeleteInfo(row.id).then((data)=> {
                                if (data.success) {
                                    this.deleteUserId = row.id
                                    this.confrimDelete.show(new ConfirmInfo("删除", data.result + "你确定删除这个用户以及相关关联信息？"))
                                } else {
                                    this.promptService.warning(data.error.message)
                                }
                            });
                        }
                    }
                }],
            responseHandler: (res: any) => {
                console.log(res)
                if (!res.success) {
                    this.promptService.warning(res.error.message)
                }
                return {
                    // "total": res.result.total,//总页数
                    // "rows": res.result.items   //数据
                    "total": res.paginator.total,
                    "rows": res.result   //数据
                };
            }
        })
    }

    showAddUserModal() {
        if (this.userEditForm.id) {
            this.userEditForm = new UserEditForm()
        }
        $(this.editModal.nativeElement).modal("show");
    }

    getDeleteResult(result: any) {
        if (result) {
            this.userService.deleteUser(this.deleteUserId).then((data)=> {
                if (data.success) {
                    $(this.table.nativeElement).bootstrapTable("refresh")
                    this.promptService.info(data.result)
                } else {
                    this.promptService.warning(data.error.message)
                }
            })
        }
    }

    editUser() {


        if (this.userEditForm.username == undefined || this.userEditForm.username == "") {
            this.promptService.warning("请输入账号")
            return false
        }

        if (this.userEditForm.realname == undefined || this.userEditForm.realname == "") {
            this.promptService.warning("请输入真实姓名")
            return false
        }

        if (this.commonService.emptyStr(this.userEditForm.tel)) {
            this.promptService.warning("请输入联系电话")
            return false
        } else {
            let numbers: any[] = this.userEditForm.tel.split(",")
            for (let number of numbers) {
                if (isNaN(number)) {
                    this.promptService.warning("联系电话格式不对")
                    return false
                }
            }
        }


        if (!this.userEditForm.id || (this.userEditForm.id && this.userEditForm.isSetPassword == 'true')) {
            if (this.userEditForm.password == undefined || this.userEditForm.password == "") {
                this.promptService.warning("请输入密码")
                return false
            }


            if (this.userEditForm.repassword == undefined || this.userEditForm.repassword == "") {
                this.promptService.warning("请输入确认密码")
                return false
            }

            if (this.userEditForm.password != this.userEditForm.repassword) {
                this.promptService.warning("两次密码不一致")
                return false
            }

        }


        if (this.userEditForm.roleId == undefined) {
            this.promptService.warning("请选择角色")
            return false
        }


        this.userService.editUser(this.userEditForm).then((data)=> {
            if (data.success) {
                $(this.table.nativeElement).bootstrapTable("refresh")
                $(this.editModal.nativeElement).modal("hide");
                this.userEditForm = new UserEditForm()
                this.promptService.info(data.result)
            } else {
                this.promptService.warning(data.error.message)
            }
        });
    }


}